<template>
  <view class="note-detail">
    <!-- Header with back button and title -->
    <view class="header">
      <uni-icons type="arrow-left" size="24" @click="goBack" />
      <text class="title">笔记详情</text>
    </view>

    <!-- Main content area -->
    <view class="content">
      <!-- Note title -->
      <view class="title-section">
        <input 
          v-if="isEditing"
          v-model="editingNote.title"
          class="note-title edit-input"
          placeholder="输入标题"
        />
        <text v-else class="note-title">{{ note.title || '无标题' }}</text>
        <view class="edit-buttons">
          <view v-if="isEditing" class="cancel-btn" @click="cancelEdit">
            <uni-icons 
              type="close" 
              size="24" 
              color="#ff6b6b"
            ></uni-icons>
          </view>
          <view class="edit-btn" @click="toggleEdit">
            <uni-icons 
              :type="isEditing ? (isSaving ? 'spinner' : 'checkmark') : 'compose'" 
              size="24" 
              :color="isEditing ? '#4caf50' : '#64b5f6'"
              :class="{ loading: isSaving }"
            ></uni-icons>
          </view>
        </view>
      </view>

      <!-- Note metadata -->
      <view class="metadata">
        <text class="timestamp">{{ note.lastEditTime }}</text>
        <view class="actions">
          <uni-icons 
            type="trash" 
            size="24" 
            color="#ff6b6b"
            @click="confirmDelete"
          />
        </view>
      </view>

      <!-- Note content -->
      <view class="note-content">
        <textarea 
          v-if="isEditing"
          v-model="editingNote.content"
          class="edit-textarea"
          placeholder="输入内容"
          auto-height
          @input="updateWordCount"
        />
        <view v-else class="markdown-content">
          <rich-text :nodes="parseMarkdown(note.content)" />
        </view>
        <text v-if="isEditing" class="word-count">
          字数：{{ wordCount }} / 5000
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import _ from 'lodash'

export default {
  data() {
    return {
      note: {
        id: null,
        title: '',
        content: '',
        lastEditTime: ''
      },
      isEditing: false,
      isSaving: false,
      wordCount: 0,
      editingNote: {
        title: '',
        content: ''
      }
    }
  },
  onBackPress() {
    uni.switchTab({
      url: '/pages/home/index'
    })
    return true
  },
  onLoad(options) {
    if (options.id) {
      this.fetchNoteDetails(options.id)
    }
  },
  methods: {
    confirmDelete() {
      uni.showModal({
        title: '删除笔记',
        content: '确定要删除该笔记吗？此操作不可恢复',
        confirmColor: '#ff6b6b',
        success: (res) => {
          if (res.confirm) {
            this.deleteNote()
          }
        }
      })
    },
    async deleteNote() {
      try {
        // TODO: Implement actual delete API call
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('Failed to delete note:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    },
    async fetchNoteDetails(noteId) {
      try {
        const response = await import('@/test/mockNotes.json')
        const note = response.default.find(n => n.id === Number(noteId))
        
        if (note) {
          this.note = {
            id: note.id,
            title: note.title,
            content: note.content,
            lastEditTime: note.lastEditTime || new Date().toLocaleString()
          }
        }
      } catch (error) {
        console.error('Failed to load note:', error)
        uni.showToast({
          title: '加载笔记失败',
          icon: 'none'
        })
      }
    },
    goBack() {
      uni.navigateBack()
    },
    updateWordCount() {
      this.wordCount = this.editingNote.content.length
    },
    
    parseMarkdown(content) {
      if (!content) return []
      // Enhanced markdown parsing
      const nodes = []
      let inCodeBlock = false
      let codeContent = ''
      let inQuote = false
      let quoteContent = ''
      let inTable = false
      let tableRows = []
      
      content.split('\n').forEach(line => {
        // Handle code blocks
        if (line.startsWith('```')) {
          if (inCodeBlock) {
            // End of code block
            nodes.push({
              name: 'pre',
              attrs: { class: 'markdown-code-block' },
              children: [{
                name: 'code',
                attrs: { class: 'markdown-code' },
                children: [{ type: 'text', text: codeContent }]
              }]
            })
            codeContent = ''
            inCodeBlock = false
          } else {
            // Start of code block
            inCodeBlock = true
          }
          return
        }

        // Handle quotes
        if (line.startsWith('> ')) {
          if (!inQuote) {
            inQuote = true
            quoteContent = line.slice(2)
          } else {
            quoteContent += '\n' + line.slice(2)
          }
          return
        } else if (inQuote) {
          nodes.push({
            name: 'blockquote',
            attrs: { class: 'markdown-quote' },
            children: [{
              name: 'p',
              children: [{ type: 'text', text: quoteContent }]
            }]
          })
          inQuote = false
          quoteContent = ''
        }
        
        if (inCodeBlock) {
          codeContent += line + '\n'
          return
        }

        // Handle inline code and links
        const inlineCodeMatches = line.match(/`([^`]+)`/g)
        const linkMatches = line.match(/\[(.*?)\]\((.*?)\)/g)
        
        if (inlineCodeMatches || linkMatches) {
          let text = line
          
          if (inlineCodeMatches) {
            inlineCodeMatches.forEach(match => {
              const codeContent = match.slice(1, -1)
              text = text.replace(
                match,
                `<code class="markdown-inline-code">${codeContent}</code>`
              )
            })
          }
          
          if (linkMatches) {
            linkMatches.forEach(match => {
              const [_, linkText, linkUrl] = match.match(/\[(.*?)\]\((.*?)\)/)
              text = text.replace(
                match,
                `<a href="${linkUrl}" class="markdown-link">${linkText}</a>`
              )
            })
          }
          
          nodes.push({
            name: 'p',
            attrs: { class: 'markdown-paragraph' },
            children: [{ type: 'html', text }]
          })
          return
        }

        // Handle images
        const imageMatch = line.match(/!\[(.*?)\]\((.*?)\)/)
        if (imageMatch) {
          nodes.push({
            name: 'img',
            attrs: {
              class: 'markdown-image',
              src: imageMatch[2],
              alt: imageMatch[1]
            }
          })
          return
        }

        // Handle headings
        if (line.startsWith('#')) {
          const level = line.match(/^#+/)[0].length
          nodes.push({
            name: `h${level}`,
            attrs: { class: 'markdown-heading' },
            children: [{ type: 'text', text: line.replace(/^#+\s*/, '') }]
          })
          return
        }

        // Handle lists
        if (line.startsWith('- ')) {
          nodes.push({
            name: 'li',
            attrs: { class: 'markdown-list-item' },
            children: [{ type: 'text', text: line.slice(2) }]
          })
          return
        }

        // Handle task lists
        if (line.match(/^- \[[ xX]\] /)) {
          const isChecked = line[3].toLowerCase() === 'x'
          nodes.push({
            name: 'li',
            attrs: { class: 'markdown-task-item' },
            children: [
              {
                name: 'input',
                attrs: {
                  type: 'checkbox',
                  checked: isChecked,
                  disabled: true
                }
              },
              {
                type: 'text',
                text: line.slice(6)
              }
            ]
          })
          return
        }

        // Handle horizontal rules
        if (line.match(/^(-{3,}|_{3,}|\*{3,})$/)) {
          nodes.push({
            name: 'hr',
            attrs: { class: 'markdown-hr' }
          })
          return
        }

        // Handle tables
        if (line.match(/^\|.+\|$/)) {
          if (!inTable) {
            inTable = true
            tableRows = []
          }
          tableRows.push(line.split('|').slice(1, -1).map(cell => cell.trim()))
          return
        } else if (inTable) {
          // End of table
          if (tableRows.length > 1) {
            const [header, ...rows] = tableRows
            nodes.push({
              name: 'table',
              attrs: { class: 'markdown-table' },
              children: [
                {
                  name: 'thead',
                  children: [{
                    name: 'tr',
                    children: header.map(cell => ({
                      name: 'th',
                      children: [{ type: 'text', text: cell }]
                    }))
                  }]
                },
                {
                  name: 'tbody',
                  children: rows.map(row => ({
                    name: 'tr',
                    children: row.map(cell => ({
                      name: 'td',
                      children: [{ type: 'text', text: cell }]
                    }))
                  }))
                }
              ]
            })
          }
          inTable = false
          tableRows = []
        }

        // Handle paragraphs
        nodes.push({
          name: 'p',
          attrs: { class: 'markdown-paragraph' },
          children: [{ type: 'text', text: line }]
        })
      })
      
      return nodes
    },
    
    cancelEdit() {
      this.isEditing = false
      this.editingNote = {
        title: this.note.title,
        content: this.note.content
      }
    },

    async toggleEdit() {
      if (this.isEditing) {
        // Validate input
        if (!this.editingNote.title.trim()) {
          uni.showToast({
            title: '标题不能为空',
            icon: 'none'
          })
          return
        }
        
        if (!this.editingNote.content.trim()) {
          uni.showToast({
            title: '内容不能为空', 
            icon: 'none'
          })
          return
        }

        try {
          this.isSaving = true
          
          // Simulate save delay
          await new Promise(resolve => setTimeout(resolve, 800))
          
          // Update note
          this.note = {
            ...this.note,
            title: this.editingNote.title,
            content: this.editingNote.content,
            lastEditTime: new Date().toLocaleString()
          }
          
          uni.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 1500
          })
          
          // Exit edit mode after successful save
          this.isEditing = false
          
          // Navigate back to home after short delay
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/home/index'
            })
          }, 1600)
        } catch (error) {
          console.error('保存失败:', error)
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          })
        } finally {
          this.isSaving = false
        }
      } else {
        // Start editing - copy current values
        this.editingNote = {
          title: this.note.title,
          content: this.note.content
        }
        this.isEditing = true
      }
    },

    // Handle navigation away with unsaved changes
    onBackPress() {
      if (this.isEditing) {
        uni.showModal({
          title: '未保存的更改',
          content: '您有未保存的更改，确定要离开吗？',
          confirmColor: '#ff6b6b',
          success: (res) => {
            if (res.confirm) {
              uni.switchTab({
                url: '/pages/home/index'
              })
            }
          }
        })
        return true
      }
      uni.switchTab({
        url: '/pages/home/index'
      })
      return true
    },

    // Auto-save when editing
    autoSave() {
      if (this.isEditing && !this.isSaving) {
        this.debouncedSave()
      }
    },

    // Debounced save function
    debouncedSave: _.debounce(function() {
      if (this.editingNote.title.trim() && this.editingNote.content.trim()) {
        this.toggleEdit()
      }
    }, 3000)
  }
}
</script>

<style scoped lang="scss">
.note-detail {
  padding: 24px;
  min-height: 100vh;
  background: linear-gradient(180deg, rgba(66, 174, 198, 0.171) 0%, rgba(255,255,255,1) 100%);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('https://source.unsplash.com/random/1920x1080?nature') no-repeat center center/cover;
    opacity: 0.2;
    z-index: -1;
    filter: blur(4px);
  }
  
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(circle at 50% 50%, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%);
    z-index: -1;
    animation: float 6s ease-in-out infinite;
  }

  .particles {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
    overflow: hidden;

    .particle {
      position: absolute;
      width: 2px;
      height: 2px;
      background: rgba(255, 255, 255, 0.5);
      border-radius: 50%;
      animation: particle-float linear infinite;
      opacity: 0.8;

      @for $i from 1 through 50 {
        &:nth-child(#{$i}) {
          $size: random(4) + 1;
          $duration: random(10) + 5;
          $delay: random(10);
          $x: random(100);
          $y: random(100);
          
          width: #{$size}px;
          height: #{$size}px;
          top: #{$y}vh;
          left: #{$x}vw;
          animation-duration: #{$duration}s;
          animation-delay: #{$delay}s;
        }
      }
    }
  }
}

@keyframes particle-float {
  0% {
    transform: translateY(0) scale(1);
    opacity: 0.8;
  }
  50% {
    transform: translateY(-20px) scale(1.2);
    opacity: 1;
  }
  100% {
    transform: translateY(-40px) scale(1);
    opacity: 0;
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  backdrop-filter: blur(10px);
  
  .title {
    font-size: 20px;
    font-weight: bold;
    margin-left: 0;
    text-align: center;
    color: #2c3e50;
    flex: 1;
  }
}

.content {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  backdrop-filter: blur(10px);
  position: relative;
}

.title-section {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0,0,0,0.05);
  
  .note-title {
    font-size: 24px;
    font-weight: 600;
    color: #2c3e50;
    flex: 1;
    font-family: 'PingFang SC', sans-serif;
  }
  
  .edit-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    
    .cancel-btn {
      padding: 8px;
      border-radius: 50%;
      transition: all 0.2s ease;
      cursor: pointer;
      position: relative;
      
      &:hover {
        background: rgba(255, 107, 107, 0.1);
        transform: scale(1.1);
      }
      
      &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border-radius: 50%;
        border: 2px solid transparent;
        transition: all 0.3s ease;
      }
      
      &:active::after {
        border-color: rgba(255, 107, 107, 0.3);
        transform: scale(1.2);
      }
    }
    
    .edit-btn {
      padding: 8px;
      border-radius: 50%;
      transition: all 0.2s ease;
      cursor: pointer;
      position: relative;
      
      &:hover {
        background: rgba(100, 181, 246, 0.1);
        transform: scale(1.1);
      }
      
      &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border-radius: 50%;
        border: 2px solid transparent;
        transition: all 0.3s ease;
      }
      
      &:active::after {
        border-color: rgba(100, 181, 246, 0.3);
        transform: scale(1.2);
      }
      
      .loading {
        animation: spin 1s linear infinite;
      }
    }
  }
}

.metadata {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0,0,0,0.05);
  
  .timestamp {
    font-size: 14px;
    color: #666;
    opacity: 0.8;
  }
  
  .actions {
    display: flex;
    gap: 16px;
    
    .icon {
      padding: 8px;
      border-radius: 50%;
      transition: all 0.2s ease;
      cursor: pointer;
      
      &:hover {
        background: rgba(255, 107, 107, 0.1);
        transform: scale(1.1);
      }
    }
  }
}

.note-content {
  font-size: 16px;
  line-height: 1.8;
  color: #444;
  white-space: pre-wrap;
  font-family: 'PingFang SC', sans-serif;
  
  &::first-letter {
    font-size: 1.5em;
    font-weight: bold;
    color: #64b5f6;
  }
}

.edit-input {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  border: none;
  outline: none;
  width: 100%;
  padding: 8px;
  margin: 0;
  background: rgba(245, 245, 245, 0.5);
  border-radius: 8px;
  transition: all 0.2s ease;
  
  &:focus {
    background: rgba(245, 245, 245, 0.8);
    box-shadow: 0 0 0 2px rgba(100, 181, 246, 0.5);
  }
}

.markdown-content {
  table.markdown-table {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;
    
    th, td {
      padding: 8px;
      border: 1px solid rgba(0,0,0,0.1);
    }
    
    th {
      background: rgba(100, 181, 246, 0.1);
      font-weight: bold;
    }
    
    tr:hover {
      background: rgba(0,0,0,0.03);
    }
  }

  blockquote.markdown-quote {
    border-left: 4px solid #64b5f6;
    margin: 16px 0;
    padding: 8px 16px;
    background: rgba(100, 181, 246, 0.05);
    color: #666;
    font-style: italic;
    
    p {
      margin: 0;
    }
  }

  pre.markdown-code-block {
    background: rgba(0,0,0,0.05);
    padding: 16px;
    border-radius: 8px;
    margin: 16px 0;
    overflow-x: auto;
    
    code.markdown-code {
      font-family: 'Courier New', monospace;
      font-size: 14px;
      white-space: pre-wrap;
    }
  }
  
  img.markdown-image {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    margin: 16px 0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  width: 100%;
  
  .markdown-heading {
    font-weight: bold;
    margin: 16px 0 8px;
    
    &.h1 { font-size: 24px; }
    &.h2 { font-size: 22px; }
    &.h3 { font-size: 20px; }
    &.h4 { font-size: 18px; }
    &.h5 { font-size: 16px; }
    &.h6 { font-size: 14px; }
  }
  
  .markdown-list-item {
    margin-left: 24px;
    list-style-type: disc;
  }

  .markdown-task-item {
    margin-left: 24px;
    list-style-type: none;
    display: flex;
    align-items: center;
    
    input {
      margin-right: 8px;
    }
  }

  .markdown-hr {
    border: 0;
    height: 1px;
    background: rgba(0,0,0,0.1);
    margin: 24px 0;
  }
  
  .markdown-paragraph {
    margin: 8px 0;
    line-height: 1.6;
    
    code.markdown-inline-code {
      background: rgba(0,0,0,0.05);
      padding: 2px 4px;
      border-radius: 4px;
      font-family: 'Courier New', monospace;
      font-size: 90%;
      color: #d63384;
    }
    
    a.markdown-link {
      color: #64b5f6;
      text-decoration: none;
      border-bottom: 1px solid rgba(100, 181, 246, 0.3);
      transition: all 0.2s ease;
      position: relative;
      padding-bottom: 2px;
      
      &:hover {
        color: #4caf50;
        border-bottom-color: rgba(76, 175, 80, 0.5);
        
        &::after {
          content: '';
          position: absolute;
          left: 0;
          right: 0;
          bottom: -2px;
          height: 2px;
          background: rgba(76, 175, 80, 0.3);
          animation: link-underline 0.3s ease-out;
          transform-origin: left;
        }
      }
      
      &:active {
        color: #388e3c;
        border-bottom-color: rgba(56, 142, 60, 0.5);
        transform: translateY(1px);
      }
      
      &:focus {
        outline: none;
        box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.3);
        animation: link-focus 0.3s ease-out;
      }
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: -2px;
        height: 2px;
        background: rgba(76, 175, 80, 0.1);
        transform: scaleX(0);
        transform-origin: right;
        transition: transform 0.3s ease;
      }
      
      &:hover::before {
        transform: scaleX(1);
        transform-origin: left;
      }
      
      &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: -2px;
        height: 2px;
        background: rgba(76, 175, 80, 0.3);
        transform: scaleX(0);
        transform-origin: right;
        transition: transform 0.3s ease;
      }
      
      &:hover::after {
        transform: scaleX(1);
        transform-origin: left;
      }
      
      &::before,
      &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: -2px;
        height: 2px;
        background: rgba(76, 175, 80, 0.3);
        transform: scaleX(0);
        transform-origin: right;
        transition: transform 0.3s ease;
      }
      
      &::before {
        bottom: -4px;
        background: rgba(76, 175, 80, 0.1);
      }
      
      &:hover::before,
      &:hover::after {
        transform: scaleX(1);
        transform-origin: left;
      }
    }

    @keyframes link-underline {
      from {
        transform: scaleX(0);
        opacity: 0;
      }
      50% {
        opacity: 1;
      }
      to {
        transform: scaleX(1);
      }
    }

    @keyframes link-focus {
      0% {
        box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.3);
      }
      50% {
        box-shadow: 0 0 0 4px rgba(76, 175, 80, 0.3);
      }
      100% {
        box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.3);
      }
    }
  }
}

.word-count {
  position: absolute;
  right: 24px;
  bottom: 16px;
  font-size: 12px;
  color: #666;
  opacity: 0.8;
}

.edit-textarea {
  font-size: 16px;
  line-height: 1.8;
  color: #444;
  width: 100%;
  border: none;
  outline: none;
  padding: 12px;
  margin: 0;
  resize: none;
  background: rgba(245, 245, 245, 0.5);
  border-radius: 8px;
  min-height: 200px;
  transition: all 0.2s ease;
  
  &:focus {
    background: rgba(245, 245, 245, 0.8);
    box-shadow: 0 0 0 2px rgba(100, 181, 246, 0.5);
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
